msg_tool\scripts\artemis\ast/
types.rs

1use std::cmp::{PartialEq, PartialOrd};
2use std::convert::From;
3use std::ops::{Deref, Index, IndexMut};
4
5#[derive(Clone, Debug, PartialEq)]
6/// Represents a value in LUA table
7pub enum Value {
8    /// Float number
9    Float(f64),
10    /// Integer number
11    Int(i64),
12    /// String value
13    Str(String),
14    /// Key value pair
15    KeyVal((Box<Value>, Box<Value>)),
16    /// Array of values
17    Array(Vec<Value>),
18    /// Null(nli) value
19    Null,
20}
21
22impl From<String> for Value {
23    fn from(s: String) -> Self {
24        Value::Str(s)
25    }
26}
27
28impl<'a> From<&'a str> for Value {
29    fn from(s: &'a str) -> Self {
30        Value::Str(s.to_string())
31    }
32}
33
34impl From<i64> for Value {
35    fn from(i: i64) -> Self {
36        Value::Int(i)
37    }
38}
39
40impl From<f64> for Value {
41    fn from(f: f64) -> Self {
42        Value::Float(f)
43    }
44}
45
46/// Reprsents a key in nested arrays.
47/// For example, in the array `{"save", text="test"}`, the key is `"save"`.
48pub struct Key<'a>(pub &'a str);
49
50/// Represents a key in key value pairs.
51/// For example, in the key value pair `[1] = "test"`, the key is `1`.
52#[derive(Clone, Copy)]
53pub struct NumKey<T: Clone + Copy>(pub T);
54
55impl<'a> Deref for Key<'a> {
56    type Target = str;
57
58    fn deref(&self) -> &Self::Target {
59        &self.0
60    }
61}
62
63const NULL: Value = Value::Null;
64
65impl Value {
66    /// Returns a reference to the string if the value is a string, otherwise returns None.
67    pub fn as_str(&self) -> Option<&str> {
68        if let Value::Str(s) = self {
69            Some(s)
70        } else {
71            None
72        }
73    }
74
75    /// Returns a string if the value is a string, otherwise returns None.
76    pub fn as_string(&self) -> Option<String> {
77        if let Value::Str(s) = self {
78            Some(s.clone())
79        } else {
80            None
81        }
82    }
83
84    /// Find a nested array by key (first value of nested array).
85    /// If the key is not found, it returns a reference to `NULL`.
86    ///
87    /// # Example
88    /// ```lua
89    /// {
90    ///    {"save", text="test"},
91    /// }
92    /// ```
93    /// for above array, calling `find_array("save")` will return the entire array `{"save", text="test"}`.
94    pub fn find_array(&self, key: &str) -> &Value {
95        match self {
96            Value::Array(arr) => {
97                for item in arr {
98                    if &item[0] == key {
99                        return item;
100                    }
101                }
102                &NULL
103            }
104            _ => &NULL,
105        }
106    }
107
108    /// Find a nested array by key (first value of nested array).
109    /// If the key is not found, it creates a new array with the key and returns a mutable reference to it.
110    ///
111    /// # Example
112    /// ```lua
113    /// {
114    ///    {"save", text="test"},
115    /// }
116    /// ```
117    /// for above array, calling `find_array_mut("save")` will return a mutable reference to the array `{"save", text="test"}`.
118    pub fn find_array_mut(&mut self, key: &str) -> &mut Value {
119        match &self {
120            Value::Array(arr) => {
121                for (i, item) in arr.iter().enumerate() {
122                    if &item[0] == key {
123                        return &mut self[i];
124                    }
125                }
126                self.push_member(Value::Array(vec![Value::Str(key.to_string())]));
127                self.last_member_mut()
128            }
129            _ => {
130                *self = Value::Array(vec![Value::Str(key.to_string())]);
131                self.last_member_mut()
132            }
133        }
134    }
135
136    /// Returns true if the value is an array.
137    pub fn is_array(&self) -> bool {
138        matches!(self, Value::Array(_))
139    }
140
141    /// Returns true if the value is a string.
142    pub fn is_str(&self) -> bool {
143        matches!(self, Value::Str(_))
144    }
145
146    /// Returns true if the value is a key-value pair.
147    pub fn is_kv(&self) -> bool {
148        matches!(self, Value::KeyVal(_))
149    }
150
151    /// Returns true if the value is null.
152    pub fn is_null(&self) -> bool {
153        matches!(self, Value::Null)
154    }
155
156    /// Returns the key of a key-value pair if it exists, otherwise returns None.
157    pub fn kv_key(&self) -> Option<&Value> {
158        if let Value::KeyVal((k, _)) = self {
159            Some(&k)
160        } else {
161            None
162        }
163    }
164
165    /// Returns the keys in a lua table.
166    pub fn kv_keys<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Value> + 'a> {
167        match self {
168            Value::KeyVal((k, _)) => Box::new(std::iter::once(&**k)),
169            Value::Array(arr) => Box::new(arr.iter().filter_map(|v| v.kv_key())),
170            _ => Box::new(std::iter::empty()),
171        }
172    }
173
174    /// Returns the last member of the array if it exists, otherwise returns a reference to `NULL`.
175    pub fn last_member(&self) -> &Value {
176        match self {
177            Value::Array(arr) => arr.last().unwrap_or(&NULL),
178            _ => &NULL,
179        }
180    }
181
182    /// Returns a mutable reference to the last member of the array.
183    ///
184    /// If the array is empty, it creates a new member with `NULL` and returns it.
185    /// If the value is not an array, it converts it to an array with a single `NULL` member.
186    pub fn last_member_mut(&mut self) -> &mut Value {
187        match self {
188            Value::Array(arr) => {
189                if arr.is_empty() {
190                    arr.push(NULL);
191                }
192                arr.last_mut().unwrap()
193            }
194            _ => {
195                *self = Value::Array(vec![NULL]);
196                self.last_member_mut()
197            }
198        }
199    }
200
201    /// Returns the length of the array.
202    pub fn len(&self) -> usize {
203        match self {
204            Value::Array(arr) => arr.len(),
205            _ => 0,
206        }
207    }
208
209    /// Inserts a member at the specified index in the array.
210    ///
211    /// If the index is out of bounds, it appends the value to the end of the array.
212    /// If the value is not an array, it converts it to an array with a single member.
213    pub fn insert_member(&mut self, index: usize, value: Value) {
214        match self {
215            Value::Array(arr) => {
216                if index < arr.len() {
217                    arr.insert(index, value);
218                } else {
219                    arr.push(value);
220                }
221            }
222            _ => {
223                *self = Value::Array(vec![value]);
224            }
225        }
226    }
227
228    /// Returns an iterator over the members of the array.
229    pub fn members<'a>(&'a self) -> Iter<'a> {
230        match self {
231            Value::Array(arr) => Iter { iter: arr.iter() },
232            _ => Iter::default(),
233        }
234    }
235
236    /// Returns a mutable iterator over the members of the array.
237    pub fn members_mut<'a>(&'a mut self) -> IterMut<'a> {
238        match self {
239            Value::Array(arr) => IterMut {
240                iter: arr.iter_mut(),
241            },
242            _ => IterMut::default(),
243        }
244    }
245
246    /// Creates a new empty array.
247    pub fn new_array() -> Self {
248        Value::Array(Vec::new())
249    }
250
251    /// Creates a new key-value pair.
252    pub fn new_kv<K: Into<Value>, V: Into<Value>>(key: K, value: V) -> Self {
253        Value::KeyVal((Box::new(key.into()), Box::new(value.into())))
254    }
255
256    /// Pushes a member to the end of the array.
257    pub fn push_member(&mut self, value: Value) {
258        match self {
259            Value::Array(arr) => arr.push(value),
260            _ => {
261                *self = Value::Array(vec![value]);
262            }
263        }
264    }
265
266    /// Sets the value to a string.
267    pub fn set_str<S: AsRef<str> + ?Sized>(&mut self, value: &S) {
268        *self = Value::Str(value.as_ref().to_string());
269    }
270
271    /// Sets the value to a string.
272    pub fn set_string<S: Into<String>>(&mut self, value: S) {
273        *self = Value::Str(value.into());
274    }
275}
276
277impl Index<usize> for Value {
278    type Output = Value;
279
280    fn index(&self, index: usize) -> &Self::Output {
281        match self {
282            Value::Array(arr) => {
283                if index < arr.len() {
284                    &arr[index]
285                } else {
286                    &NULL
287                }
288            }
289            _ => &NULL,
290        }
291    }
292}
293
294impl IndexMut<usize> for Value {
295    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
296        match self {
297            Value::Array(arr) => {
298                if index < arr.len() {
299                    &mut arr[index]
300                } else {
301                    arr.push(NULL);
302                    arr.last_mut().unwrap()
303                }
304            }
305            _ => {
306                *self = Value::Array(vec![NULL]);
307                self.index_mut(0)
308            }
309        }
310    }
311}
312
313impl<'a> Index<&'a str> for Value {
314    type Output = Value;
315
316    fn index(&self, key: &'a str) -> &Self::Output {
317        match self {
318            Value::KeyVal((k, v)) if k == key => v,
319            Value::Array(arr) => {
320                for item in arr.iter().rev() {
321                    if let Value::KeyVal((k, v)) = item {
322                        if k == key {
323                            return v;
324                        }
325                    }
326                }
327                &NULL
328            }
329            _ => &NULL,
330        }
331    }
332}
333
334impl<'a> IndexMut<&'a str> for Value {
335    fn index_mut(&mut self, index: &'a str) -> &mut Self::Output {
336        match &self {
337            Value::KeyVal((k, _)) => {
338                if k == index {
339                    if let Value::KeyVal((_, v)) = self {
340                        v
341                    } else {
342                        unreachable!()
343                    }
344                } else {
345                    *self = Value::KeyVal((Box::new(index.to_string().into()), Box::new(NULL)));
346                    if let Value::KeyVal((_, v)) = self {
347                        v
348                    } else {
349                        unreachable!()
350                    }
351                }
352            }
353            Value::Array(arr) => {
354                for (i, item) in arr.iter().enumerate().rev() {
355                    if let Value::KeyVal((k, _)) = item {
356                        if k == index {
357                            if let Value::KeyVal((_, v)) = &mut self[i] {
358                                return v;
359                            } else {
360                                unreachable!()
361                            }
362                        }
363                    }
364                }
365                if let Value::Array(arr) = self {
366                    arr.push(Value::KeyVal((
367                        Box::new(index.to_string().into()),
368                        Box::new(NULL),
369                    )));
370                    if let Value::KeyVal((_, v)) = arr.last_mut().unwrap() {
371                        v
372                    } else {
373                        unreachable!()
374                    }
375                } else {
376                    unreachable!()
377                }
378            }
379            _ => {
380                *self = Value::Array(vec![Value::KeyVal((
381                    Box::new(index.to_string().into()),
382                    Box::new(NULL),
383                ))]);
384                self.index_mut(index)
385            }
386        }
387    }
388}
389
390impl<'a> Index<&'a String> for Value {
391    type Output = Value;
392
393    #[inline(always)]
394    fn index(&self, key: &'a String) -> &Self::Output {
395        self.index(key.as_str())
396    }
397}
398
399impl<'a> IndexMut<&'a String> for Value {
400    #[inline(always)]
401    fn index_mut(&mut self, index: &'a String) -> &mut Self::Output {
402        self.index_mut(index.as_str())
403    }
404}
405
406impl Index<String> for Value {
407    type Output = Value;
408
409    #[inline(always)]
410    fn index(&self, key: String) -> &Self::Output {
411        self.index(key.as_str())
412    }
413}
414
415impl IndexMut<String> for Value {
416    #[inline(always)]
417    fn index_mut(&mut self, index: String) -> &mut Self::Output {
418        self.index_mut(index.as_str())
419    }
420}
421
422impl<'a> Index<&'a Value> for Value {
423    type Output = Value;
424
425    fn index(&self, key: &'a Value) -> &Self::Output {
426        match self {
427            Value::KeyVal((k, v)) if k == key => v,
428            Value::Array(arr) => {
429                for item in arr.iter().rev() {
430                    if let Value::KeyVal((k, v)) = item {
431                        if k == key {
432                            return v;
433                        }
434                    }
435                }
436                &NULL
437            }
438            _ => &NULL,
439        }
440    }
441}
442
443impl<'a> IndexMut<&'a Value> for Value {
444    fn index_mut(&mut self, index: &'a Value) -> &mut Self::Output {
445        match &self {
446            Value::KeyVal((k, _)) => {
447                if k == index {
448                    if let Value::KeyVal((_, v)) = self {
449                        v
450                    } else {
451                        unreachable!()
452                    }
453                } else {
454                    *self = Value::KeyVal((Box::new(index.clone()), Box::new(NULL)));
455                    if let Value::KeyVal((_, v)) = self {
456                        v
457                    } else {
458                        unreachable!()
459                    }
460                }
461            }
462            Value::Array(arr) => {
463                for (i, item) in arr.iter().enumerate().rev() {
464                    if let Value::KeyVal((k, _)) = item {
465                        if k == index {
466                            if let Value::KeyVal((_, v)) = &mut self[i] {
467                                return v;
468                            } else {
469                                unreachable!()
470                            }
471                        }
472                    }
473                }
474                if let Value::Array(arr) = self {
475                    arr.push(Value::KeyVal((Box::new(index.clone()), Box::new(NULL))));
476                    if let Value::KeyVal((_, v)) = arr.last_mut().unwrap() {
477                        v
478                    } else {
479                        unreachable!()
480                    }
481                } else {
482                    unreachable!()
483                }
484            }
485            _ => {
486                *self = Value::Array(vec![Value::KeyVal((
487                    Box::new(index.clone()),
488                    Box::new(NULL),
489                ))]);
490                self.index_mut(index)
491            }
492        }
493    }
494}
495
496impl<'a> Index<&'a Box<Value>> for Value {
497    type Output = Value;
498
499    #[inline(always)]
500    fn index(&self, key: &'a Box<Value>) -> &Self::Output {
501        self.index(&**key)
502    }
503}
504
505impl Index<NumKey<i64>> for Value {
506    type Output = Value;
507
508    fn index(&self, key: NumKey<i64>) -> &Self::Output {
509        match self {
510            Value::KeyVal((k, v)) if k == key.0 => v,
511            Value::Array(arr) => {
512                for item in arr.iter().rev() {
513                    if let Value::KeyVal((k, v)) = item {
514                        if k == key.0 {
515                            return v;
516                        }
517                    }
518                }
519                &NULL
520            }
521            _ => &NULL,
522        }
523    }
524}
525
526impl IndexMut<NumKey<i64>> for Value {
527    fn index_mut(&mut self, key: NumKey<i64>) -> &mut Self::Output {
528        match &self {
529            Value::KeyVal((k, _)) => {
530                if k == key.0 {
531                    if let Value::KeyVal((_, v)) = self {
532                        v
533                    } else {
534                        unreachable!()
535                    }
536                } else {
537                    *self = Value::KeyVal((Box::new(key.0.into()), Box::new(NULL)));
538                    if let Value::KeyVal((_, v)) = self {
539                        v
540                    } else {
541                        unreachable!()
542                    }
543                }
544            }
545            Value::Array(arr) => {
546                for (i, item) in arr.iter().enumerate().rev() {
547                    if let Value::KeyVal((k, _)) = item {
548                        if k == key.0 {
549                            if let Value::KeyVal((_, v)) = &mut self[i] {
550                                return v;
551                            } else {
552                                unreachable!()
553                            }
554                        }
555                    }
556                }
557                if let Value::Array(arr) = self {
558                    arr.push(Value::KeyVal((Box::new(key.0.into()), Box::new(NULL))));
559                    if let Value::KeyVal((_, v)) = arr.last_mut().unwrap() {
560                        v
561                    } else {
562                        unreachable!()
563                    }
564                } else {
565                    unreachable!()
566                }
567            }
568            _ => {
569                *self = Value::Array(vec![Value::KeyVal((
570                    Box::new(key.0.into()),
571                    Box::new(NULL),
572                ))]);
573                self.index_mut(key)
574            }
575        }
576    }
577}
578
579impl Index<NumKey<f64>> for Value {
580    type Output = Value;
581
582    fn index(&self, key: NumKey<f64>) -> &Self::Output {
583        match self {
584            Value::KeyVal((k, v)) if k == key.0 => v,
585            Value::Array(arr) => {
586                for item in arr.iter().rev() {
587                    if let Value::KeyVal((k, v)) = item {
588                        if k == key.0 {
589                            return v;
590                        }
591                    }
592                }
593                &NULL
594            }
595            _ => &NULL,
596        }
597    }
598}
599
600impl IndexMut<NumKey<f64>> for Value {
601    fn index_mut(&mut self, key: NumKey<f64>) -> &mut Self::Output {
602        match &self {
603            Value::KeyVal((k, _)) => {
604                if k == key.0 {
605                    if let Value::KeyVal((_, v)) = self {
606                        v
607                    } else {
608                        unreachable!()
609                    }
610                } else {
611                    *self = Value::KeyVal((Box::new(key.0.into()), Box::new(NULL)));
612                    if let Value::KeyVal((_, v)) = self {
613                        v
614                    } else {
615                        unreachable!()
616                    }
617                }
618            }
619            Value::Array(arr) => {
620                for (i, item) in arr.iter().enumerate().rev() {
621                    if let Value::KeyVal((k, _)) = item {
622                        if k == key.0 {
623                            if let Value::KeyVal((_, v)) = &mut self[i] {
624                                return v;
625                            } else {
626                                unreachable!()
627                            }
628                        }
629                    }
630                }
631                if let Value::Array(arr) = self {
632                    arr.push(Value::KeyVal((Box::new(key.0.into()), Box::new(NULL))));
633                    if let Value::KeyVal((_, v)) = arr.last_mut().unwrap() {
634                        v
635                    } else {
636                        unreachable!()
637                    }
638                } else {
639                    unreachable!()
640                }
641            }
642            _ => {
643                *self = Value::Array(vec![Value::KeyVal((
644                    Box::new(key.0.into()),
645                    Box::new(NULL),
646                ))]);
647                self.index_mut(key)
648            }
649        }
650    }
651}
652
653impl<'a, 'b> Index<&'b Key<'a>> for Value {
654    type Output = Value;
655
656    #[inline(always)]
657    fn index(&self, key: &'b Key<'a>) -> &Self::Output {
658        self.find_array(&key.0)
659    }
660}
661
662impl<'a, 'b> IndexMut<&'b Key<'a>> for Value {
663    #[inline(always)]
664    fn index_mut(&mut self, key: &'b Key<'a>) -> &mut Self::Output {
665        self.find_array_mut(&key.0)
666    }
667}
668
669impl<'a> Index<Key<'a>> for Value {
670    type Output = Value;
671
672    #[inline(always)]
673    fn index(&self, key: Key<'a>) -> &Self::Output {
674        self.find_array(&key.0)
675    }
676}
677
678impl<'a> IndexMut<Key<'a>> for Value {
679    #[inline(always)]
680    fn index_mut(&mut self, key: Key<'a>) -> &mut Self::Output {
681        self.find_array_mut(&key.0)
682    }
683}
684
685impl PartialEq<str> for Value {
686    fn eq(&self, other: &str) -> bool {
687        match self {
688            Value::Str(s) => s == other,
689            _ => false,
690        }
691    }
692}
693
694impl PartialEq<String> for Value {
695    fn eq(&self, other: &String) -> bool {
696        self == other.as_str()
697    }
698}
699
700impl PartialEq<i64> for Value {
701    fn eq(&self, other: &i64) -> bool {
702        match self {
703            Value::Int(i) => i == other,
704            _ => false,
705        }
706    }
707}
708
709impl PartialEq<f64> for Value {
710    fn eq(&self, other: &f64) -> bool {
711        match self {
712            Value::Float(f) => f == other,
713            _ => false,
714        }
715    }
716}
717
718impl PartialEq<str> for Box<Value> {
719    #[inline(always)]
720    fn eq(&self, other: &str) -> bool {
721        **self == *other
722    }
723}
724
725impl PartialEq<String> for Box<Value> {
726    #[inline(always)]
727    fn eq(&self, other: &String) -> bool {
728        **self == *other
729    }
730}
731
732impl PartialEq<i64> for Box<Value> {
733    #[inline(always)]
734    fn eq(&self, other: &i64) -> bool {
735        **self == *other
736    }
737}
738
739impl PartialEq<f64> for Box<Value> {
740    #[inline(always)]
741    fn eq(&self, other: &f64) -> bool {
742        **self == *other
743    }
744}
745
746impl PartialEq<Value> for Box<Value> {
747    #[inline(always)]
748    fn eq(&self, other: &Value) -> bool {
749        **self == *other
750    }
751}
752
753impl<'a> PartialEq<i64> for &'a Box<Value> {
754    #[inline(always)]
755    fn eq(&self, other: &i64) -> bool {
756        **self == *other
757    }
758}
759
760impl<'a> PartialEq<f64> for &'a Box<Value> {
761    #[inline(always)]
762    fn eq(&self, other: &f64) -> bool {
763        **self == *other
764    }
765}
766
767impl PartialOrd<i64> for Value {
768    fn partial_cmp(&self, other: &i64) -> Option<std::cmp::Ordering> {
769        match self {
770            Value::Int(i) => i.partial_cmp(other),
771            _ => None,
772        }
773    }
774}
775
776impl PartialOrd<f64> for Value {
777    fn partial_cmp(&self, other: &f64) -> Option<std::cmp::Ordering> {
778        match self {
779            Value::Float(f) => f.partial_cmp(other),
780            _ => None,
781        }
782    }
783}
784
785impl PartialOrd<i64> for Box<Value> {
786    #[inline(always)]
787    fn partial_cmp(&self, other: &i64) -> Option<std::cmp::Ordering> {
788        (**self).partial_cmp(other)
789    }
790}
791
792impl PartialOrd<f64> for Box<Value> {
793    #[inline(always)]
794    fn partial_cmp(&self, other: &f64) -> Option<std::cmp::Ordering> {
795        (**self).partial_cmp(other)
796    }
797}
798
799#[derive(Default)]
800/// An iterator over the members of an array.
801pub struct Iter<'a> {
802    iter: std::slice::Iter<'a, Value>,
803}
804
805impl<'a> Iterator for Iter<'a> {
806    type Item = &'a Value;
807
808    #[inline(always)]
809    fn next(&mut self) -> Option<Self::Item> {
810        self.iter.next()
811    }
812}
813
814impl<'a> ExactSizeIterator for Iter<'a> {
815    #[inline(always)]
816    fn len(&self) -> usize {
817        self.iter.len()
818    }
819}
820
821impl<'a> DoubleEndedIterator for Iter<'a> {
822    #[inline(always)]
823    fn next_back(&mut self) -> Option<Self::Item> {
824        self.iter.next_back()
825    }
826}
827
828#[derive(Default)]
829/// A mutable iterator over the members of an array.
830pub struct IterMut<'a> {
831    iter: std::slice::IterMut<'a, Value>,
832}
833
834impl<'a> Iterator for IterMut<'a> {
835    type Item = &'a mut Value;
836
837    #[inline(always)]
838    fn next(&mut self) -> Option<Self::Item> {
839        self.iter.next()
840    }
841}
842
843impl<'a> ExactSizeIterator for IterMut<'a> {
844    #[inline(always)]
845    fn len(&self) -> usize {
846        self.iter.len()
847    }
848}
849
850impl<'a> DoubleEndedIterator for IterMut<'a> {
851    #[inline(always)]
852    fn next_back(&mut self) -> Option<Self::Item> {
853        self.iter.next_back()
854    }
855}
856
857#[derive(Clone, Debug)]
858/// Represents an AST file.
859pub struct AstFile {
860    /// The version of the AST file.
861    pub astver: Option<f64>,
862    /// The name of the AST file.
863    pub astname: Option<String>,
864    /// The data of the AST file.
865    pub ast: Value,
866}